/*
 * @FileName: bsp.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-07-12 16:05:59
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-20 13:25:50
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#include "bsp.h"

typedef void (*vfunc_t)(void);

void bsp_init(void) {

//        /* Unlocks the FLASH Program Erase Controller */
//    FLASH_Unlock();
//    
//    if(FLASH_Read_Out_Protection_Status_Get() == SET)
//    {
//        log_debug("Flash has entered the read-protected L1 state\r\n");
//        //FLASH_Read_Out_Protection_L1_Disable();
//    }
//    else
//    {
//        log_debug("Enable read protection L1\r\n");
//        FLASH_Read_Out_Protection_L1_Enable();
//        /* Generate System Reset to load the new option byte values */
//        log_debug("Software reset\r\n");
//        NVIC_SystemReset();
//    }
//    
//    /* Locks the FLASH Program Erase Controller */
//    FLASH_Lock();

    FLASH_Prefetch_Buffer_Enable();
    NVIC_Priority_Group_Set(NVIC_PER2_SUB2_PRIORITYGROUP);
    bsp_gpio_init();
    bsp_uart_init();
    bsp_adc_init();
    bsp_pwm_init();

}

/**
 * @description: 跳转至APP或者BOOT
 * @param  addr BOOT地址或者APP地址
 * @return {*}
 */
void bsp_jump_to(uint32_t addr)
{
    volatile uint32_t goal_addr = 0;
    vfunc_t reset_handle = 0;

    goal_addr = *((volatile uint32_t *)(addr + 4));
    reset_handle = (vfunc_t)goal_addr;
    __set_MSP(*(__IO uint32_t*)addr);
    reset_handle();
}

/**
 * @description: 看门狗初始化，复位周期10秒
 */
void bsp_wdg_init(void)
{
    DBG_Peripheral_ON(DBG_IWDG_STOP);
    IWDG_Write_Protection_Disable();
    IWDG_Key_Reload();
    IWDG_Prescaler_Division_Set(IWDG_CONFIG_PRESCALER_DIV128);
    IWDG_Counter_Reload(312);
    IWDG_Key_Reload();
    IWDG_Enable();
    IWDG_Write_Protection_Enable();
}

/**
 * @description: 喂狗
 */
void bsp_wdg_feed(void)
{
    IWDG_Key_Reload();
}

void bsp_enter_stanby(void)
{
    /* Enable PWR clock */
    RCC_APB1_Peripheral_Clock_Enable(RCC_APB1_PERIPH_PWR);
    /* Enable WKUP pin */
    PWR_Wakeup_Pin_Enable(WAKEUP_PIN1, PWR_PIN_FALLING);

    /* Check if the Wake-Up flag is set */
    if (PWR_Flag_Status_Get(PWR_WKUP_FLAG_PA8) != RESET)
    {
        /* Clear Wake Up flag */
        PWR_Flag_Status_Clear(PWR_WKUP_FLAG_PA8);
    }
    PWR_STANDBY_Mode_Enter(PWR_STANDBY_ENTRY_WFI);
}
